package Gin教程

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// 用来对网站资源的访问保护
var secrets = gin.H{
	"foo":    gin.H{"email": "foo@bar.com", "phone": "123456"},
	"austin": gin.H{"email": "austin@bar.com", "phone": "223456"},
	"lena":   gin.H{"email": "lena@bar.com", "phone": "123456"},
}

func Handler(c *gin.Context) {
	//获取用户，它是 basicauth 中间件设置的
	user := c.MustGet(gin.AuthUserKey).(string)
	fmt.Println(user)
	if secret, ok := secrets[user]; ok {
		c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
	} else {
		c.JSON(http.StatusOK, gin.H{"user": user, "secret": "no secret:("})
	}

}
func main() {
	r := gin.Default()

	//路由组使用 gin.BasicAuth() 中间件
	// gin.Accounts{} 是map[string]string 的一种快捷方式
	auth := r.Group("/admin", gin.BasicAuth(gin.Accounts{
		"foo":    "bar",
		"austin": "1234",
		"lena":   "hello",
	}))

	// adimin/serect 终点
	auth.GET("/serect", Handler)
	r.Run(":8081")
}
